package com.customization.unionpay.market.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.InnovativeSettlementUtils;
import com.customization.unionpay.market.util.MPManagePlatformUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 营销退款明细台账，调用创新结算系统支付状态查询接口
 */
public class SyncMarketFundingPayStateJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncMarketFundingPayStateJob.class);

    public void execute() {

        RecordSet rs = new RecordSet();

        RecordSetTrans rst = new RecordSetTrans();

        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {

            // 营销退款明细台账表单id
            int refundDetailsFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_refund_details_form_id"));

            String tableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(refundDetailsFormId);

            String yhysl = com.customization.unionpay.market.util.FormDataUtils.getItemValue(refundDetailsFormId, "zfzt", "银行已受理");
            String qsyc = com.customization.unionpay.market.util.FormDataUtils.getItemValue(refundDetailsFormId, "zfzt", "清算异常");
            String wzddyjl = FormDataUtils.getItemValue(refundDetailsFormId, "zfzt", "未找到对应记录");

            if (StrUtil.isNotBlank(yhysl) && StrUtil.isNotBlank(qsyc) && StrUtil.isNotBlank(wzddyjl)) {
                if (StrUtil.isNotBlank(tableName)) {

                    JSONObject jh = new JSONObject();
                    String sql = "select tkdh,lyxt from #{tableName} where zfzt = ? or zfzt = ?  or zfzt = ? ";
                    sql = sql.replace("#{tableName}",tableName);
                    log.info("sql:"+sql);
                    // 查询营销活动事项台账活动是否核销为否的数据
                    rs.executeQuery(sql,yhysl,qsyc,wzddyjl);

                    List<String> codes = new ArrayList<>();
                    while (rs.next()) {
                        String tkdh = Util.null2String(rs.getString("tkdh"));
                        String lyxt = Util.null2String(rs.getString("lyxt"));
                        if (!"".equals(tkdh)) {
                            if (!codes.contains(tkdh)) {
                                codes.add(tkdh);
                                jh.put(tkdh,lyxt);
                            }
                        }
                    }
                    log.info("jh:"+jh);
                    // 判断集合是否大于0
                    if (codes.size() > 0) {
                        JSONObject params = new JSONObject();
                        params.put("mpmKeyList",codes);
                        try {
                            String resultStr = InnovativeSettlementUtils.queryPayState(params);
                            log.info("返回参数：" + resultStr);

                            JSONObject resultJson = JSONObject.parseObject(resultStr);

                            String code = resultJson.getString("code");
                            if ("0000".equals(code)) {
                                JSONObject json = resultJson.getJSONObject("resp");

                                JSONArray data = json.getJSONArray("transPayRecStBriefList");
                                log.info("解析data参数：" + data);

                                for (int i = 0; i < data.size(); i++) {
                                    JSONObject single = data.getJSONObject(i);
                                    // 业务流水号
                                    String mpmKey = single.getString("mpmKey");
                                    // 划付记录状态
                                    int recSt = single.getInteger("recSt")-1;

                                    try {

                                        StringBuilder updateSql = new StringBuilder(" update ");
                                        updateSql.append(tableName);
                                        updateSql.append(" set zfzt='");
                                        updateSql.append(recSt);
                                        updateSql.append("'  where tkdh ='");
                                        updateSql.append(mpmKey);
                                        updateSql.append("' ");
                                        log.info("updateSql:" + updateSql.toString());
                                        // 修改累计充值金额
                                        rst.executeUpdate(updateSql.toString());
                                        // 提交事务
                                        rst.commit();

                                        if(3 == recSt){
                                            String lyxt = jh.getString(mpmKey);
                                            log.info("lyxt：" + lyxt);
                                            if(lyxt != null && !"".equals(lyxt)){
                                                // 推送营销项目管理平台支付状态
                                                String innovativePush = MPManagePlatformUtils.createInnovativePush(mpmKey, "支付成功");
                                                log.error("推送营销项目管理平台支付状态返回值：" + innovativePush);
                                                JSONObject innovativePushJson = JSONObject.parseObject(innovativePush);
                                                String codeIP = innovativePushJson.getString("code");
                                                if (!"200".equals(codeIP)){
                                                    String message = resultJson.getString("message");
                                                    log.error("请求失败：" + message);
                                                }
                                            }else {
                                                log.info("当前退款单不是营销项目管理平台发起，不需要推送营销项目管理平台！");
                                            }

                                        }

                                    } catch (Exception e) {
                                        // 回滚
                                        rst.rollback();
                                        log.error("修改数据异常：" + e.getMessage());
                                    }
                                }
                            } else {
                                String msg = resultJson.getString("msg");
                                log.error("请求失败：" + msg);
                                updateErrorRemark(tableName,msg,codes);
                            }
                        } catch (Exception e) {
                            log.error("修改数据异常：" + e.getMessage());
                            String message = e.getMessage();
                            updateErrorRemark(tableName,message,codes);
                        }
                    }
                } else {
                    log.error("根据营销退款明细台账表单formId查询数据库表名失败！");
                }
            } else {
                log.error("zfzt枚举为空或找不到！");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }

    /**
     * 修改失败原因
     */
    private void updateErrorRemark(String tableName,String msg,List<String> codes){
        RecordSetTrans rst = new RecordSetTrans();
        try {
            StringBuilder updateSql = new StringBuilder("update ");
            updateSql.append(tableName);
            updateSql.append(" set  zfsbyy='");
            updateSql.append(msg);
            updateSql.append("' where tkdh in (");
            codes.forEach(o->{
                updateSql.append("'").append(o).append("'").append(",");
            });
            updateSql.deleteCharAt(updateSql.length()-1).append(")");
            log.info("updateSql:"+updateSql);
            rst.executeUpdate(updateSql.toString());
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
        }
    }
}

